<template>
  <div>
    点评此书
    <h1>添加评论页面</h1>
    <van-field
      v-model="message"
      rows="2"
      name="message"
      autosize
      label="评论"
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />

    <!-- 渲染评论区域 -->

    <div style="display: inline-block">
      <van-button type="info" style="margin: 16px" @click="onCancel">
        取消
      </van-button>
      <van-button type="info" style="margin: 16px" @click="onConfirm">
        提交
      </van-button>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'addComments',
  data() {
    return {
      message: '',
    }
  },
  computed: { ...mapState(['commentsArr', 'userInfo', 'cacheCommentsArr']) },
  created() {
    this.getCacheArr()
  },
  activated() {
    this.getCacheArr()
  },

  methods: {
    ...mapMutations(['set_comments_arr', 'set_cache_commentsArr']),
    getCacheArr() {
      this.message = this.cacheCommentsArr.filter(
        (v) => v?.idBookCard === this.$route.params.id
      )[0]?.message
    },
    onConfirm() {
      if (this.message) {
        let obj = {
          id: Date.now(),
          idBookCard: this.$route.params.id,
          message: this.message,
          userInfo: this.userInfo,
          like: false,
        }
        this.message = ''
        this.set_comments_arr(obj)
        // 将上一次缓存的数据在发布成功之后，清空
        this.set_cache_commentsArr(null)
        // 评论成功之后之后，跳转到详情页面
        this.$router.push(`/detail/${this.$route.params.id}`)
      } else {
        this.$toast('请输入数据再提交')
      }
    },
    onCancel() {
      this.$dialog
        .alert({
          message: '确认取消吗？',
        })
        .then((res) => {
          console.log('res:确认取消，并且缓存数据')
          // 1. 可以通过keep-alive 可以缓存住数据，下次进来重新发布
          // 2. 可以通过本地存储，缓存住数据
          let obj = {
            id: Date.now(),
            idBookCard: this.$route.params.id,
            message: this.message,
            userInfo: this.userInfo,
            like: false,
          }
          this.set_cache_commentsArr(obj)
          this.$router.go(-1)
        })
        .catch((er) => {
          console.log('取消缓存不缓存数据')
        })
    },
  },
}
</script>

<style></style>
